<?php
/**
 * Created by PhpStorm.
 * User: xi
 * Date: 2020-05-02
 * Time: 16:54
 */

namespace app\api\service;


use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\Shopmeituan;
use app\admin\model\Shopmtdyprofit;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproombook;
use app\admin\model\Shopstaff;
use app\admin\model\Shoptableorder;
use app\admin\model\Usermeituancode;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userwithdraw;

/**
 * 最新的美团平台
 */
class MeituanService
{

    protected $appKey = "";
    protected $secret = "";
    protected $developerId = 113494;
    protected $signKey = "8vdppaflku20575o";

    public function prepare($req)
    {

        $url = "https://api-open-cater.meituan.com/ddzh/tuangou/receipt/prepare";//输码验券校验

        $shopModel = new Shop();
        $shop = $shopModel->where('id', $req['shop_id'])->find();

        $param = array();
        $param['businessId'] = 58;
        $param['charset'] = "UTF-8";
        $param['appAuthToken'] = $shop['mt2_token'];
        $param['timestamp'] = time();
        $param['developerId'] = $this->developerId;
        $param['version'] = 2;

        $biz = array();
        $biz['receiptCode'] = $req['code'];
        $param['biz'] = json_encode($biz);
        $param['sign'] = $this->get_sign($this->signKey, $param);

        $result = $this->curl_post($url, $param);
        $ret = array();

        if ($result['code'] == 'OP_SUCCESS') {
            $ret['msg'] = "成功";
            $ret['code'] = 200;
            $ret['traceId'] = $result['traceId'];
            $ret['data']['deal_id'] = $result['data']['dealId'];
            $ret['data']['dealgroup_id'] = $result['data']['dealGroupId'];
            return $ret;
        } else {
            $ret['msg'] = $result['msg'];
            $ret['code'] = 199;
            return $ret;
        }

    }


    public function getProductList($req)
    {

        $url = "https://api-open-cater.meituan.com/ddzh/tuangou/deal/queryshopdeal";//获取团购信息

        $shopModel = new Shop();
        $shop = $shopModel->where('id', $req['shop_id'])->find();
        $param = array();
        $param['businessId'] = 58;
        $param['charset'] = "UTF-8";
        $param['appAuthToken'] = $shop['mt2_token'];
        $param['timestamp'] = time();
        $param['developerId'] = $this->developerId;
        $param['version'] = 2;

        $biz = array();
        $biz['offset'] = 1;
        $biz['limit'] = 100;
        $biz['source'] = 2;

        $param['biz'] = json_encode($biz);
        $param['sign'] = $this->get_sign($this->signKey, $param);

        $result = $this->curl_post($url, $param);

        return $result;

    }

    public function consume($order)
    {

        $url = "https://api-open-cater.meituan.com/ddzh/tuangou/receipt/consume";//验券

        $userMeituanCode = new Usermeituancode();
        $shopMtCode = new Shopmeituan();
        $shopModel = new Shop();

        $meituan = $userMeituanCode->where('mt_code', $order['mt_code'])->find();
        $shopMtInfo = $shopMtCode->where('id', $meituan['group_id'])->find();
        $shop = $shopModel->where('id', $meituan['shop_id'])->find();

        $code = $order['mt_code'];

        $param = array();
        $param['businessId'] = 58;
        $param['charset'] = "UTF-8";
        $param['appAuthToken'] = $shop['mt2_token'];
        $param['timestamp'] = time();
        $param['developerId'] = $this->developerId;
        $param['version'] = 2;

        $biz = array();
        $biz['receiptCode'] = $code;
        $biz['count'] = 1;
        $biz['requestId'] = "qx_" . getOrderSn();
        $biz['appShopAccountName'] = "雀侠";
        $biz['appShopAccount'] = "quexia2000";

        $param['biz'] = json_encode($biz);
        $param['sign'] = $this->get_sign($this->signKey, $param);

        $result = $this->curl_post($url, $param);
        $isChecked = 0;

        //error_log(json_encode($param)."==meituan=consume==".json_encode($result));

        if ($result['code'] == 'OP_SUCCESS') {
            $userMeituanCode->where('mt_code', $order['mt_code'])->update(['status' => 'used']);
            $isChecked = 1;
            $price = $result['data']['result'][0]['dealPrice'];
            $payList = $result['data']['result'][0]['paymentDetail'];
            $amount = $result['data']['result'][0]['dealPrice'];
            foreach ($payList as $key => $val) {
                if ($val['amountType'] == 10 && $val['amount'] > 0) {
                    $price = $val['amount'];
                }
            }
            $tableOrderModel = new Shoptableorder();
            $shopMtDyModel = new Shopmtdyprofit();
            $db = $tableOrderModel->where('order_no', $order['order_no'])->find();

            //判断是否有叠加核销的券
            if ($shopMtInfo['price'] * 1.2 < $price) {
                $price = $shopMtInfo['price'];
            }
            if ($db) {
                $tableOrderModel->where('id', $order['id'])->update(['amount' => $price]);
                if ($shop['is_all'] == 1) {
                    $shopMtDyModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'origin_amount' => $amount, 'amount' => $price, 'create_time' => time(), 'type' => 'meituan', 'order_type' => 'tq', 'profit' => $price * $shop['ratio'] / 100]);
                }
            } else {
                $shopOrderModel = new Shoporder();
                $shopOrderModel->where('id', $order['id'])->update(['amount' => $price]);
                if ($shop['is_all'] == 1) {
                    $shopMtDyModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'origin_amount' => $amount, 'amount' => $price, 'create_time' => time(), 'type' => 'meituan', 'order_type' => 'qp', 'profit' => $price * $shop['ratio'] / 100]);
                }
            }

        }
        return $isChecked;
    }

    //出现同时用美团券和支付现金的情况下，需要返回美团券用户支付金额
    public function newConsume($order)
    {

        $url = "https://api-open-cater.meituan.com/ddzh/tuangou/receipt/consume";//验券

        $userMtModel = new Usermeituancode();
        //$userMtModel->where('mt_code', $order['mt_code'])->update(['status' => 'lock']);
        $userMeituanCode = new Usermeituancode();
        $shopModel = new Shop();
        $meituan = $userMeituanCode->where('mt_code', $order['mt_code'])->find();
        $shop = $shopModel->where('id', $meituan['shop_id'])->find();

        $code = $order['mt_code'];

        $param = array();
        $param['businessId'] = 58;
        $param['charset'] = "UTF-8";
        $param['appAuthToken'] = $shop['mt2_token'];
        $param['timestamp'] = time();
        $param['developerId'] = $this->developerId;
        $param['version'] = 2;

        $biz = array();
        $biz['receiptCode'] = $code;
        $biz['count'] = 1;
        $biz['requestId'] = "qx_" . getOrderSn();
        $biz['appShopAccountName'] = "雀侠";
        $biz['appShopAccount'] = "quexia2000";

        $param['biz'] = json_encode($biz);
        $param['sign'] = $this->get_sign($this->signKey, $param);

        $result = $this->curl_post($url, $param);
        $price = 0;

        //error_log(json_encode($param)."==meituan=consume==".json_encode($result));

        if ($result['code'] == 'OP_SUCCESS') {
            $userMtModel->where('mt_code', $order['mt_code'])->update(['status' => 'used']);
            $price = $result['data']['result'][0]['dealPrice'];
            $payList = $result['data']['result'][0]['paymentDetail'];
            $amount = $result['data']['result'][0]['dealPrice'];
            foreach ($payList as $key => $val) {
                if ($val['amountType'] == 10 && $val['amount'] > 0) {
                    $price = $val['amount'];
                }
            }
            $tableOrderModel = new Shoptableorder();
            $shopMtDyModel = new Shopmtdyprofit();
            $db = $tableOrderModel->where('order_no', $order['order_no'])->find();
            if ($db) {
                $tableOrderModel->where('id', $order['id'])->update(['amount' => $price]);
                if ($shop['is_all'] == 1) {
                    $shopMtDyModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'origin_amount' => $amount, 'amount' => $price, 'create_time' => time(), 'type' => 'meituan', 'order_type' => 'tq', 'profit' => $price * $shop['ratio'] / 100]);
                }
            } else {
                $shopOrderModel = new Shoporder();
                $shopOrderModel->where('id', $order['id'])->update(['amount' => $price]);
                if ($shop['is_all'] == 1) {
                    $shopMtDyModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'origin_amount' => $amount, 'amount' => $price, 'create_time' => time(), 'type' => 'meituan', 'order_type' => 'qp', 'profit' => $price * $shop['ratio'] / 100]);
                }
            }

        }
        return $price;
    }


    public function refreshToken($req)
    {

        $developerId = $this->developerId;
        $signKey = $this->signKey;
        $businessId = 58;
        $charset = "UTF-8";
        $grantType = "refresh_token";
        $timestamp = time();
        $param = array();
        $param['businessId'] = $businessId;
        $param['charset'] = $charset;
        $param['scope'] = "all";
        $param['developerId'] = $developerId;
        $param['grantType'] = $grantType;
        $param['timestamp'] = $timestamp;
        $param['refreshToken'] = $req['refreshToken'];
        $param['sign'] = $this->get_sign($signKey, $param);

        $url = "https://api-open-cater.meituan.com/oauth/refresh";

        $result = $this->curl_post($url, $param);
        if ($result['code'] == 0) {
            $accessToken = $result['data']['accessToken'];
            $expireIn = $result['data']['expireIn'];
            $refreshToken = $result['data']['refreshToken'];
            $opBizName = $result['data']['opBizName'];
            $opBizCode = $result['data']['opBizCode'];

            $shopModel = new Shop();
            $shopModel->where('id', $req['shop_id'])->update(['mt2_token' => $accessToken, 'mt2_refresh_token' => $refreshToken, 'mt2_update_time' => strtotime("+ " . $expireIn . " seconds")]);
        }
    }

    public function curl_post($url, $postdata)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Expect:'
        )); //
        $post_data = http_build_query($postdata);//重点

        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        //curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


    function get_sign($sign_key, $data)
    {
        if ($data == null) {
            return null;
        }
        ksort($data);
        $result_str = "";
        foreach ($data as $key => $val) {
            if ($key != null && $key != "" && $key != "sign") {
                $result_str = $result_str . $key . $val;
            }
        }
        $result_str = $sign_key . $result_str;


        $ret = bin2hex(sha1($result_str, true));

        return $ret;
    }


}